package com.fgs.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.fgs.common.R;
import com.fgs.common.utils.CommonUtil;
import com.xuexiang.xui.utils.ResUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @author fgs
 * @date 2020/3/29
 * @description
 **/
public class TabSwitchView extends LinearLayout {
    private int mEntriesID;
    private int mEntriesValueID;
    private String mTitle;
    private int mTitleTextColor;
    private TextView mTipTextView;
    private TextView mTitleTextView;
    private RadioGroup mRadioGroup;
    private int mTabPadding;
    private int mTabPaddingLeft;
    private int mTabPaddingRight;
    private int mTabMargin;
    private int mTabHeight;
    private float mTabTextSize;
    private boolean mTabEnable;
    private boolean mIsTipShow;
    private int mTabType;
    private final LinkedHashMap<String, String> mTabMap = new LinkedHashMap<>();
    private final LinkedHashMap<String, Integer> mTabMapPosition = new LinkedHashMap<>();

    private List<RadioButton> mOptions;
    private int mDrawableId = R.drawable.bg_tab;
    private int mDefaultSelection = -1;
    private OnTabCheckedChangeListener mOnTabCheckedChangeListener;

    public TabSwitchView(Context context) {
        super(context);
        initView(context, null);
    }

    public TabSwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TabSwitchView);
        try {
            mTitle = typedArray.getString(R.styleable.TabSwitchView_TabSwitchTitle);
            mIsTipShow = typedArray.getBoolean(R.styleable.TabSwitchView_TabSwitchIsShowTip, false);
            mTitleTextColor = typedArray.getColor(R.styleable.TabSwitchView_TabSwitchTitleTextColor, getResources().getColor(R.color.colorTextBlack));
            mEntriesID = typedArray.getResourceId(R.styleable.TabSwitchView_TabSwitchEntries, 0);
            mEntriesValueID = typedArray.getResourceId(R.styleable.TabSwitchView_TabSwitchEntriesValue, 0);
            mTabMargin = typedArray.getDimensionPixelSize(R.styleable.TabSwitchView_TabSwitchTabMargin, (int) CommonUtil.convertDpToPixel(0));
            mTabPadding = typedArray.getDimensionPixelSize(R.styleable.TabSwitchView_TabSwitchTabPadding, (int) CommonUtil.convertDpToPixel(10));
            mTabPaddingLeft = typedArray.getDimensionPixelSize(R.styleable.TabSwitchView_TabSwitchTabPaddingLeft, (int) CommonUtil.convertDpToPixel(10));
            mTabPaddingRight = typedArray.getDimensionPixelSize(R.styleable.TabSwitchView_TabSwitchTabPaddingRight, (int) CommonUtil.convertDpToPixel(10));
            mDrawableId = typedArray.getResourceId(R.styleable.TabSwitchView_TabSwitchTabBackgroundDrawable, R.drawable.bg_tab);
            mDefaultSelection = typedArray.getInteger(R.styleable.TabSwitchView_TabSwitchDefaultPosition, 0);
            mTabHeight = typedArray.getDimensionPixelSize(R.styleable.TabSwitchView_TabSwitchTabHeight, -2);
            mTabEnable = typedArray.getBoolean(R.styleable.TabSwitchView_TabSwitchTabEnable, true);
            mTabTextSize = typedArray.getFloat(R.styleable.TabSwitchView_TabSwitchTabTextSize, 14);
            mTabType = typedArray.getInt(R.styleable.TabSwitchView_TabSwitchTabType, 0);
        } finally {
            typedArray.recycle();
        }


        View view = LayoutInflater.from(context).inflate(R.layout.layout_tab_switch, null);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(layoutParams);
        addView(view);

        mTitleTextView = view.findViewById(R.id.layout_tab_switch_titleTextView);
        mTipTextView = view.findViewById(R.id.layout_click_item_tipTextView);
        mRadioGroup = view.findViewById(R.id.layout_tab_switch_radioGroup);
        if (mEntriesID != 0 && mEntriesValueID != 0) {
            try {
                setItems(ResUtils.getStringArray(mEntriesID), ResUtils.getStringArray(mEntriesValueID));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (mEntriesID != 0 && mEntriesValueID == 0) {
                try {
                    setItems(ResUtils.getStringArray(mEntriesID), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        setIsShowTip(mIsTipShow);
        setTitle(mTitle);
        setTitleTextColor(mTitleTextColor);
    }

    public void setIsShowTip(boolean isShowTip) {
        this.mIsTipShow = isShowTip;
        if (isShowTip) {
            mTipTextView.setVisibility(View.VISIBLE);
        } else {
            mTipTextView.setVisibility(View.INVISIBLE);
        }
    }

    public void setTitle(String title) {
        this.mTitle = title;
        mTitleTextView.setText(title);
        if (!TextUtils.isEmpty(title)) {
            mTitleTextView.setVisibility(View.VISIBLE);
        } else {
            mTitleTextView.setVisibility(View.GONE);
        }
    }

    public void setTitleTextColor(int titleTextColor) {
        this.mTitleTextColor = titleTextColor;
        mTitleTextView.setTextColor(titleTextColor);
    }


    /**
     * 为每一个选项设置 items and values
     *
     * @param itemArray
     * @param valueArray
     */
    public TabSwitchView setItems(String[] itemArray, String[] valueArray) throws Exception {
        mTabMap.clear();
        mTabMapPosition.clear();
        int itemLength = 0;
        int valueLength;

        if (itemArray != null && valueArray != null) {
            itemLength = itemArray.length;
            valueLength = valueArray.length;
            if (itemLength != valueLength) {
                throw new Exception("Item labels and value arrays must be the same size");
            }
        }


        if (itemArray != null) {
            itemLength = itemArray.length;
            if (valueArray != null) {
                for (int i = 0; i < itemLength; i++) {
                    mTabMap.put(itemArray[i], valueArray[i]);
                    mTabMapPosition.put(itemArray[i], i);
                }
            } else {
                for (int i = 0; i < itemLength; i++) {
                    mTabMap.put(itemArray[i], itemArray[i]);
                    mTabMapPosition.put(itemArray[i], i);
                }
            }
        }
//        LogUtil.print(JsonUtil.toJson(mTabMap));


        update(itemLength);

        return this;
    }

    /**
     * 更新显示
     */
    private void update(int itemLength) {
        if (itemLength == 0) return;
        mRadioGroup.removeAllViews();
        mRadioGroup.setOrientation(RadioGroup.HORIZONTAL);
        mRadioGroup.setGravity(mTabType == 0 ? Gravity.RIGHT : Gravity.CENTER);
        mOptions = new ArrayList<>();

        Iterator<Map.Entry<String, String>> iterator = mTabMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> item = iterator.next();

            RadioButton radioButton = new RadioButton(getContext());

            if (mTabType == 0) {
                radioButton.setText(item.getKey());
                radioButton.setButtonDrawable(R.drawable.bg_tab_radio_button);
                radioButton.setPadding(mTabPaddingLeft, mTabPadding, mTabPaddingRight, mTabPadding);
            } else {
                radioButton.setLayoutParams(initLayoutParams());
                radioButton.setPadding(mTabPadding, mTabPadding, mTabPadding, mTabPadding);
                radioButton.setText(item.getKey());
                radioButton.setButtonDrawable(null);
                radioButton.setGravity(Gravity.CENTER);
                radioButton.setTextSize(mTabTextSize);
                radioButton.setTextColor(getResources().getColorStateList(R.color.selector_text_color_tab_switch_view));
                radioButton.setBackground(getResources().getDrawable(mDrawableId).mutate());
                radioButton.setEnabled(mTabEnable);
            }

            mOptions.add(radioButton);
            mRadioGroup.addView(radioButton);

        }

        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mOnTabCheckedChangeListener != null) {
                    String item = ((RadioButton) (group.findViewById(checkedId))).getText().toString();
                    String value = mTabMap.get(item);
                    int position = mTabMapPosition.get(item);
                    mOnTabCheckedChangeListener.onCheckedChanged(position, item, value);
                }

            }
        });

        setDefaultSelection(mDefaultSelection);

    }

    private ViewGroup.LayoutParams initLayoutParams() {
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = mTabMargin;
        layoutParams.leftMargin = mTabMargin;
        layoutParams.rightMargin = mTabMargin;
        layoutParams.bottomMargin = mTabMargin;
        layoutParams.weight = 1;
        if (mTabHeight == -1) {
            layoutParams.height = LayoutParams.MATCH_PARENT;

        } else if (mTabHeight == -2) {
            layoutParams.height = LayoutParams.WRAP_CONTENT;
        } else {
            layoutParams.height = mTabHeight;
        }
        return layoutParams;
    }


    /**
     * 为每一个选项设置 items and values .并且设置一个默认选中的序号
     *
     * @param items
     * @param values
     * @param defaultSelection
     */
    public TabSwitchView setItems(String[] items, String[] values, int defaultSelection) throws Exception {
        if (defaultSelection > (items.length - 1)) {
            throw new Exception("Default selection cannot be greater than the number of items");
        } else {
            mDefaultSelection = defaultSelection;
            setItems(items, values);
        }

        return this;
    }

    /**
     * 设置默认选中的Tab
     *
     * @param defaultSelection
     * @return
     */
    public TabSwitchView setDefaultSelection(int defaultSelection) {
        try {
            if (defaultSelection > (mOptions.size() - 1)) {
                throw new Exception("Default selection cannot be greater than the number of items");
            } else {
                mDefaultSelection = defaultSelection;
                RadioButton radioButton = mOptions.get(defaultSelection);
                if (radioButton != null) {
                    mRadioGroup.check(radioButton.getId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }


    public interface OnTabCheckedChangeListener {
        void onCheckedChanged(int position, String item, String value);
    }

    /**
     * 设置Tab选中的监听
     *
     * @param onTabCheckedChangeListener
     */
    public void setOnTabCheckedChangeListener(OnTabCheckedChangeListener onTabCheckedChangeListener) {
        this.mOnTabCheckedChangeListener = onTabCheckedChangeListener;
    }
}
